iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 20
0

JavaScript Methods

Methods指的是object中,包含了function defined的property。

var me = {
  name: 'Azer',
  age: 18,
  introduce: function() {
    return "My name is " + this.name + ", I'm " + this.age + " years old.";    
  }
}

在JavaScript中 所有的function其實都是method,
如果某個function不屬於一個object,
這個function就是屬於global object。

The JavaScript call() Method

在一般情況下沒辦使用別的object的method,

var me = {
  name: 'Gururinbo',
  age: 18,
  maho: function() {
    return "My name is " + this.name + ", I'm " + this.age + " years old.";    
  }
}

var you = {
  name: 'Mumi',
  age: 18,
  introduce: function() {
    return "My name is " + this.name + ", I'm " + this.age + " years old.";    
  }
}

you.maho(); //you.maho is not a function

系統會告訴你 you.maho is not a function
如果使用 call() 就可以調用(invoke)別的object的method了。

me.maho.call(you) //My name is Mumi, I'm 18 years old.
you.introduce.call(me) //My name is Gururinbo, I'm 18 years old.

The call() Method with Arguments

如果要傳入 argument也是允許的:

var me = {
  name: 'Gururinbo',
  age: 18,
  maho: function(location) {
    return "My name is " + this.name + ", I'm " + this.age + " years old. Live in " + location + ".";    
  }
}

var you = {
  name: 'Mumi',
  age: 18,
  introduce: function() {
    return "My name is " + this.name + ", I'm " + this.age + " years old.";    
  }
}

me.maho.call(you, "Taiwan"); // My name is Mumi, I'm 18 years old. Live in Taiwan.

The JavaScript apply() Method

apply()call()的用法其實很類似,
用剛剛的例子:

console.log(you.introduce.apply(me)); //My name is Gururinbo, I'm 18 years old.

可以得到相同的結果,
而兩者的不同之處在於,
apply()的argument必須要是array。

var me = {
  name: 'Gururinbo',
  age: 18,
  maho: function(location, area) {
    return "My name is " + this.name + ", I'm " + this.age + " years old. Live in " + location + " " + area + ".";    
  }
}

var you = {
  name: 'Mumi',
  age: 18,
  introduce: function() {
    return "My name is " + this.name + ", I'm " + this.age + " years old.";    
  }
}

me.maho.apply(you, "Taiwan", "Taipei");
// CreateListFromArrayLike called on non-object

如果傳的不是array,會丟出錯誤訊息。
將argument改為array,

me.maho.apply(you, ["Taiwan", "Taipei"])
// My name is Mumi, I'm 18 years old. Live in Taiwan Taipei.

var locate = ["Taiwan", "Keelung"]
me.maho.apply(you, locate);
// My name is Mumi, I'm 18 years old. Live in Taiwan Keelung.

上一篇
[19] IDKJS - Function Invocation
下一篇
[21] IDKJS - Closure
系列文
我在繡房繡小主常服的日子-- 初入前端工程師的第一個小挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言